import './index.scss'
import {View, Image, Button, Text} from '@tarojs/components'
import {observer} from 'mobx-react'
import {useContext, useEffect, useState} from 'react'
import Taro, {useDidHide, useDidShow, useRouter} from '@tarojs/taro'
import {iconUrl} from '@/utils/baseUrl'
import {toHome} from '@/utils/pageRedirect'
import {uBindDev} from '@/api'
import {getStorage} from '@/utils/localstoreage'

const Confirmbinddev = () => {
  const router = useRouter()
  const [devNum, setDevNum] = useState('')
  // 可以使用所有的 React Hooks
  useEffect(() => {
    console.log('Confirmbinddev useEffect')
    let devGId = router.params.devGId as string
    let devGIdSplit = devGId.split('_')
    setDevNum(devGIdSplit[1])
  }, [router.params])
  // 对应 onShow
  useDidShow(() => {
    console.log('Confirmbinddev useDidShow')
  })
  // 对应 onHide
  useDidHide(() => {
    console.log('Confirmbinddev useDidHide')
  })

  function handleAddConfirmClick() {
    if (!router.params.devGId) return
    const userId = getStorage('userId')
    if (!userId) return
    Taro.showLoading({
      title: '添加设备中...'
    })

    uBindDev({
      devGId: router.params.devGId,
      userId: userId
    })
      .then(res => {
        Taro.hideLoading()
        Taro.showToast({
          title: '设备添加成功',
          icon: 'success'
        })
        setTimeout(() => {
          toHome()
        }, 2000)
      })
      .catch(err => {
        if (err && err.result === 'error') {
          Taro.showModal({
            content: err.msg || '设备添加失败！'
          })
        }
        Taro.hideLoading()
      })
  }

  return (
    <View className="h-screen bg-x_bg overflow-hidden">
      <Image
        src={iconUrl('bindDevSuccess.png')}
        className="block w-228 mx-auto"
      ></Image>
      <View className="my-8 text-center grid gap-y-8 text-14 text-xx_text">
        <View className=" text-18 font-bold text-success">
          二维码扫描完成
        </View>
        <View>设备编号：{devNum}</View>
      </View>
      <Button
        className="block w-120 h-40 leading-40 mx-auto mt-26 bg-primary rounded-8 text-white text-16"
        onClick={handleAddConfirmClick}
      >
        确认添加
      </Button>
      <Button
        className="block w-120 h-40 leading-40 mx-auto mt-26 border-1 border-solid border-primary_half rounded-8 text-16"
        onClick={toHome}
      >
        返回首页
      </Button>
    </View>
  )
}
export default observer(Confirmbinddev)
